#include <iostream>
#include <string>
#include <stdio.h>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define USER "root"
#define PASSWD "LxL2244156952"
#define DBNAME "test_db"

void add(MYSQL *mysql)
{
    std::string sql = "insert into stu values(null, 18, '张三'), (null, 17, '李四');";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "mysql query error:" << mysql_error(mysql) << "\n";
        return;
    }
    return;
}

void del(MYSQL *mysql)
{
    std::string sql = "delete from stu where name='李四' or name='张三';";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "mysql query error:" << mysql_error(mysql) << "\n";
        return;
    }
    return;
}

void mod(MYSQL *mysql)
{
    std::string sql = "update stu set age=15 where name='李四';";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "mysql query error:" << mysql_error(mysql) << "\n";
        return;
    }
    return;
}

void get(MYSQL *mysql)
{
    std::string sql = "select * from stu;";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "mysql query error:" << mysql_error(mysql) << "\n";
        return;
    }

    MYSQL_RES *res = mysql_store_result(mysql);
    if(res == nullptr)
    {
        std::cout << "mysql store result error:" << mysql_error(mysql) << "\n";
        return;
    }
    int row = mysql_num_rows(res);
    int col = mysql_num_fields(res);
    printf("%10s%10s%10s\n", "ID", "年龄", "姓名");
    for(int i = 0;i < row;i++)
    {
        MYSQL_ROW row_data = mysql_fetch_row(res);
        for(int j = 0;j < col;j++)
        {
            printf("%10s", row_data[j]);
        }
        printf("\n");
    }
    mysql_free_result(res);
    return;
}

int main()
{
    MYSQL *mysql = mysql_init(NULL);
    if (mysql == nullptr)
    {
        std::cout << "init mysql handle failed!\n";
        return -1;
    }

    if (mysql_real_connect(mysql, HOST, USER, PASSWD, DBNAME, 0, NULL, 0) == nullptr)
    {
        std::cout << "mysql connect error:" << mysql_error(mysql) << "\n";
        return -1;
    }

    mysql_set_character_set(mysql, "utf8");
    std::cout << "===================== add =========================\n";
    add(mysql);
    get(mysql);
    std::cout << "===================== mod =========================\n";
    mod(mysql);
    get(mysql);
    std::cout << "===================== del =========================\n";
    del(mysql);
    get(mysql);

    mysql_close(mysql);
    return 0;
}